define(['moment', 'module/moduleB/program/B02/B0213/B0213Service', 'module/moduleB/program/B02/B0223/B0223Service', 'module/moduleWIP/program/B02/B0225/B0225Service'], function () {
    return ['$scope', '$rootScope', '$filter', '$stateParams', '$mdDialog', 'config', 'MMWService', '$calculater', 'B0213Service', 'B0223Service', 'B0225Service',
        function ($scope, $rootScope, $filter, $stateParams, $mdDialog, config, $MMWService, $calculater, $B0213Service, $B0223Service, $B0225Service) {

            $scope.init = function () {
                $MMWService.PNIGList = {};
                $scope.warehouseInfo = {
                    type: '', product_warehouse: '', storage: '',
                    plot_info_detail: [],
                    wo_no: '', item_no: '', plot_no: '', erp_doc_type: ''
                };

                $scope.type = '0';
                $scope.selectedList = [];

                $scope.warehouseInfo.item_no = '';
                $scope.warehouseInfo.item_name = '';
                $scope.warehouseInfo.wo_no = '';

                $scope.warehouseInfo.select_type = 3;

                $scope.list_filter = {};
                $scope.filterSH = {};
                $scope.feedback_type = [];
                $scope.do_flag = 0;
                if(!config.cache.permissions || config.cache.permissions.indexOf('B0225')!=-1){
                    $scope.isB0225 = true;
                }
            };

            $scope.back = function () {
                $scope.$root.hideMenu();
                $scope.$root.changeProgram('home', true);
            };

            //20170505 modify by Dustdusk for 入庫查詢可以不用輸入條件
            $scope.search = function () {
                var content = {
                    wo_no: $scope.warehouseInfo.wo_no,
                    item_no: $scope.warehouseInfo.item_no,
                    type: $scope.type,
                    do_flag:$scope.do_flag
                };
                warehousePlotInfoGet(content, function (response) {
                    $scope.list_filter = {};
                    $scope.filterSH = {};
                    if(response && response.length > 0){
                        $scope.warehouseInfo.plot_info_detail = response;
                        $scope.warehouseInfo.plot_info_detail.forEach(function (detail) {
                            detail.checked = false;
                        });
                    } else {
                        $scope.warehouseInfo.plot_info_detail = [];
                        $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                    }
                });
            };

            $scope.ClickDoFlag = function(){
                if($scope.selectedList.length>0){
                    $scope.$root.showAlert($filter('translate')('B0401.msg.already_selected'));
                } else {
                    $scope.warehouseInfo.plot_info_detail = [];
                    $scope.selectedList = [];
                    if($scope.do_flag == 1){
                        $scope.do_flag = 0;
                        if(!config.cache.permissions || config.cache.permissions.indexOf('B0225')!=-1){
                            $scope.isB0225 = true;
                        }
                    } else {
                        $scope.do_flag = 1;
                        $scope.isB0225 = false;
                    }
                }
            };

            $scope.confirm = function () {
                //20170612 modify by Dustdusk for 新增select_type == 4(作廢)
                if($scope.warehouseInfo.select_type == 2 || $scope.warehouseInfo.select_type == 4){
                    //誤判
                    $scope.warehouseInfo.product_warehouse = '';//成品庫
                    $scope.warehouseInfo.product_warehouse_name = '';//成品庫
                    $scope.warehouseInfo.storage = ''; //儲位
                    $scope.warehouseInfo.storage_display = ''; //儲位
                    $scope.warehouseInfo.erp_doc_type = '';//ERP單別
                    warehousePlotProcess();
                } else if($scope.warehouseInfo.select_type == 3){
                    //報廢入庫
                    $scope.openStorage();
                } else {
                    //重工處理/讓步處理
                    $B0213Service.init({
                        plot_detail : $scope.selectedList,
                        option : $scope.warehouseInfo.select_type, //重工:0/讓步:1
                        parent : 'B0402',
                        feedback : function(){
                            //20170330 modify by megabytes for 確認存取完後清空
                              $scope.warehouseInfo.plot_info_detail = [];
                              $scope.warehouseInfo.item_no = '';
                              $scope.warehouseInfo.item_name = '';
                              $scope.warehouseInfo.wo_no = '';
                              $scope.warehouseInfo.plot_no = '';
                              $scope.selectedList = [];
                        }
                    });
                }
            };

            //20170405 modify by megabytes for 內存外顯修改
            //20170410 modify by megabytes for 改為皆顯示no
            //20170602 modify by Dustdusk for 開窗調整
            //20170602 modify by Dustdusk for 開窗取消
            //取得產品編號
            $scope.loadItemNo = function () {
                var page_mode;
                //20170704 modify by Dustdusk for 入庫產品清單查詢優化
                if($scope.type == '0'){
                    page_mode = 18;
                } else if($scope.type == '1'){
                    page_mode = 19;
                }
                $MMWService.showQueryListPNIG({
                    page_mode: page_mode,
                    pageRecord:50,
                    key:'page_no',
                    condition: [
                        {name:$filter('translate')('common.queryList.item_c'), column_name:'B.ProductNo', query_mode:'2', value:$scope.warehouseInfo.item_no||''},
                        {name:$filter('translate')('common.queryList.item_n'), column_name:'B.ProductName', query_mode:'2', value:''}
                    ],
                    header: [
                        {label:$filter('translate')('common.queryList.item_c'), code:'page_no'},
                        {label:$filter('translate')('common.queryList.item_n'), code:'page_name'}
                    ],
                    selectCode:$scope.warehouseInfo.item_no,
                    confirm : function(selectItem){
                        $scope.warehouseInfo.item_no = selectItem.page_no;
                        $scope.warehouseInfo.item_name = selectItem.page_name;
                        $scope.warehouseInfo.wo_no = '';
                    }
                });
            };

            //取得工單編號
            //20170602 modify by Dustdusk for 拿掉一定要輸入產品編號的限制
            //20170602 modify by Dustdusk for 開窗取消
            $scope.loadWoNo = function () {
                var page_mode;
                //20170704 modify by Dustdusk for 入庫工單清單查詢優化
                if($scope.type == '0'){
                    page_mode = 20;
                } else if($scope.type == '1'){
                    page_mode = 21;
                }
                $MMWService.showQueryListPNIG({
                    page_mode: page_mode,
                    pageRecord:50,
                    condition: [
                        {name:$filter('translate')('common.queryList.wo_c'), column_name:'C.MoNo', query_mode:'2', value:$scope.warehouseInfo.wo_no}
                    ],
                    header: [
                        {label:$filter('translate')('common.queryList.wo_c'), code:'page_no'}
                    ],
                    setCondition:function(conditions){
                        if($scope.warehouseInfo.item_no && $scope.warehouseInfo.item_no != '')
                            conditions.push({column_name:'B.ProductNo', query_mode:'0', value: $scope.warehouseInfo.item_no, merge_condition_model : 'AND'});

                        return conditions;
                    },
                    selectCode:$scope.warehouseInfo.wo_no,
                    confirm : function(selectItem){
                        $scope.warehouseInfo.wo_no = selectItem.page_no;
                    }
                });
            };

            $scope.pickTarget = function () {
                var targetArray = [];
                for (var i = 0; i < $scope.warehouseInfo.plot_info_detail.length; i++) {
                    if ($scope.warehouseInfo.plot_info_detail[i].plot_no.indexOf($scope.warehouseInfo.plot_no) != -1) {
                        var target = $scope.warehouseInfo.plot_info_detail[i];
                        var isOK = true;
                        if($scope.type == 0){
                            for(var j = 0 ; j < $scope.selectedList.length ; j++){
                                if($scope.selectedList[j].plot_no == target.plot_no && $scope.selectedList[j].qty == target.qty){
                                    //當兩者相同時更新產品資訊
                                    //$scope.selectedList[j].item_no = target.item_no;
                                    //$scope.selectedList[j].item_name = target.item_name;
                                    //$scope.selectedList[j].item_unit_no = target.item_unit_no;
                                    //$scope.selectedList[j].item_ver = target.item_ver;

                                    isOK = false;
                                    break;
                                }
                            }
                        }else if ($scope.type == 1){
                            for(var j = 0 ; j < $scope.selectedList.length ; j++){
                                //20180425 modify by Dustdusk for 相同生產批不同不良原因要能選擇
                                if($scope.selectedList[j].lot_serial == target.lot_serial && $scope.selectedList[j].error_no == target.error_no){
                                    isOK = false;
                                    break;
                                }
                            }
                        }

                        if(isOK){
                            target.checked = true;
                            $scope.selectedList.push(target);
                            targetArray.push(target);
                        }
                        //$scope.warehouseInfo.plot_info_detail.splice($scope.warehouseInfo.plot_info_detail.indexOf(target), 1);
                    }
                }

                targetArray.forEach(function(target){
                    $scope.warehouseInfo.plot_info_detail.splice($scope.warehouseInfo.plot_info_detail.indexOf(target), 1);
                })
            };

            //20170329 modify by megabytes for 刪除佇列部分也需要判斷是否重複問題
            $scope.returnTarget = function (index, data) {
                var searchrepeat = false;
                for(var i = 0 ; i < $scope.warehouseInfo.plot_info_detail.length ; i++){
                    if($scope.type == 0){
                        if($scope.selectedList[i].plot_no == data.plot_no && $scope.selectedList[i].qty == data.qty){
                            searchrepeat = true;
                            break;
                        }
                    }else if ($scope.type == 1){
                        if($scope.selectedList[i].lot_serial == data.lot_serial && $scope.selectedList[i].error_no == data.error_no){
                            searchrepeat = false;
                            break;
                        }
                    }
                }

                if(searchrepeat){
                    data.checked = !data.checked;
                    $scope.selectedList.splice($scope.selectedList.indexOf($scope.selectedList[index]), 1);
                }else{
                    data.checked = !data.checked;

                    //20180425 modify by Dustdusk for 當良品入庫且刪除時要回復變更前的產品
                    if($scope.type == 0 && data.joint_trigger == 'Y'){
                        data.item_no = data.old_item_no||data.item_no;
                        data.item_name = data.old_item_name||data.item_name;
                        data.item_unit_no = data.old_item_unit_no||data.item_unit_no;
                        data.item_ver = data.old_item_ver||data.item_ver;
                        delete data.joint_trigger;
                    }

                    $scope.warehouseInfo.plot_info_detail.push(data);
                    $scope.selectedList.splice($scope.selectedList.indexOf($scope.selectedList[index]), 1);
                }
            };

            $scope.itemCheck = function (index, data) {
                var msg = '';
                //20170328 modify by megabytes for 良品與不良品判斷依據不同，並判斷是否已重複選取
                //20170329 modify by megabytes for 良品判斷條件多增加數量。
                if($scope.type == 0){
                    for(var i = 0 ; i < $scope.selectedList.length ; i++){
                        if($scope.selectedList[i].plot_no == data.plot_no && $scope.selectedList[i].qty == data.qty){
                            //當兩者相同時更新產品資訊
                            //$scope.selectedList[i].item_no = data.item_no;
                            //$scope.selectedList[i].item_name = data.item_name;
                            //$scope.selectedList[i].item_unit_no = data.item_unit_no;
                            //$scope.selectedList[i].item_ver = data.item_ver;

                            msg = $filter('translate')('B0401.msg.repeat');
                            break;
                        }
                    }
                }else if ($scope.type == 1){
                    for(var i = 0 ; i < $scope.selectedList.length ; i++){
                        //20180425 modify by Dustdusk for 相同生產批不同不良原因要能選擇
                        if($scope.selectedList[i].lot_serial == data.lot_serial && $scope.selectedList[i].error_no == data.error_no){
                            msg = $filter('translate')('B0401.msg.repeat');
                            break;
                        }
                    }
                }

                if(msg != ''){
                    $scope.$root.showAlert(msg);
                } else {
                    data.checked = !data.checked;
                    $scope.selectedList.push(data);
                    $scope.warehouseInfo.plot_info_detail.splice($scope.warehouseInfo.plot_info_detail.indexOf($scope.warehouseInfo.plot_info_detail[index]), 1);
                }
            };


            $scope.openStorage = function () {
                $mdDialog.dialog(
                    'module/moduleWIP/program/B04/B0401/B0401_SearchPlot.tmp.html',
                    storageController
                );
            };

            function storageController(dialog) {
                var controller = {
                    type:$scope.type,
                    warehouseInfo: $scope.warehouseInfo,
                    //成品庫
                    loadProductWarehouse: function () {
                        // 良品 = 1 , 不良品 =3
                        var conditionvalue = 1;
                        if($scope.type == 1){
                            conditionvalue = 3;
                        } else {
                            conditionvalue = 1;
                        }
                        pageNumberInfoGet({
                            page_mode : '13',
                            query_condition_info : [
                                { column_name:'InventoryType', query_mode:'0', value:conditionvalue }
                            ]
                        }, function (response) {
                            $scope.$root.showSelect({
                                title: $filter('translate')('B0401.otherTitle.column1'),
                                label: function(item){
                                    return item.page_no + ' ('+ item.page_name +')';
                                },
                                code: 'page_no',
                                selectCode: $scope.warehouseInfo.product_warehouse,
                                list: response,
                                confirm: function (item, dialog) {
                                    dialog.hide();
                                    $scope.warehouseInfo.product_warehouse_name = item.page_name;
                                    $scope.warehouseInfo.product_warehouse = item.page_no;

                                    $scope.warehouseInfo.storage = '';
                                    $scope.warehouseInfo.storage_display = '';
                                }
                            });
                        });
                    },
                    //儲位
                    loadStorage: function () {
                        if($scope.warehouseInfo.product_warehouse != ''){
                            pageNumberInfoGet({page_mode: 14, query_condition_info :[
                                {column_name:'InventoryNo', query_mode:'0', value:$scope.warehouseInfo.product_warehouse}
                            ]}, function (response) {
                                $scope.$root.showSelect({
                                    title: $filter('translate')('B0401.otherTitle.column1'),
                                    label: function(item){
                                        return item.page_no + ' ('+ item.page_name +')';
                                    },
                                    code: 'page_no',
                                    selectCode: $scope.warehouseInfo.storage,
                                    list: response,
                                    confirm: function (item, dialog) {
                                        dialog.hide();
                                        $scope.warehouseInfo.storage = item.page_no;
                                        $scope.warehouseInfo.storage_display = item.page_name;
                                    }
                                });
                            });
                        } else {
                            $scope.$root.showAlert($filter('translate')('B0401.msg.product_warehouse_empty'));
                        }

                    },
                    loadERP: function () {
                        $rootScope.showQueryList({
                            pageRecord:50,
                            header : [
                                {label:$filter('translate')('B0216.queryList.column3_1'), code:'page_no'},
                                {label:$filter('translate')('B0216.queryList.column3_2'), code:'page_name'}
                            ],
                            query: function(conditions, feedback){
                                $MMWService.sendToServer({
                                    uri: 'ServicesSTD.Module_SYS.erp_document_type_get',
                                    content: { doc_type:$scope.do_flag == 0?'1':'6' },
                                    success: function (data) {
                                        feedback(data);
                                    }
                                });
                            },
                            selectCode:$scope.warehouseInfo.erp_doc_type,
                            confirm : function(selectItem, dialog){
                                $scope.warehouseInfo.erp_doc_type = selectItem.page_no;
                                dialog.hide();
                            }
                        });
                    },
                    back: function () {
                        $scope.warehouseInfo.product_warehouse_name = '';
                        $scope.warehouseInfo.product_warehouse = '';
                        $scope.warehouseInfo.storage = '';
                        $scope.warehouseInfo.storage_display = '';
                        $scope.warehouseInfo.erp_doc_type = '';
                        dialog.hide();
                    },
                    confirm: function () {
                        if($scope.type==0){
                            if($scope.warehouseInfo.product_warehouse.length == 0) {
                                $rootScope.showAlert($filter('translate')('B0401.showAlert.column3'));
                            } else {
                                dialog.hide();
                                warehousePlotProcess();
                            }
                        } else if($scope.type == 1){
                            dialog.hide();
                            warehousePlotProcess();
                        }
                    }
                }
                return controller;
            }

            //取得單號
            // 1 工單編號 6產品編號 13成品庫 14儲位
            function pageNumberInfoGet(content, feedback) {
                $MMWService.pageNumberInfoGet(
                    content
                    , function (itemList) {
                        feedback(itemList);
                });
            }


            //取得待入庫資料
            //type 0:良品  1:不良品
            function warehousePlotInfoGet(content, feedback) {
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.warehouse_plot_info_get',
                    content: content,
                    success: function (data) {
                        feedback(data.warehouse_plot_info_get);
                    }
                });
            }

            //送出確定的待入庫資料
            //type 0:良品 1:不良品
            function warehousePlotProcess() {
                var msg = '';
                var content = {
                    type: $scope.type,
                    product_warehouse: $scope.warehouseInfo.product_warehouse,
                    storage: $scope.warehouseInfo.storage,
                    erp_doc_type: $scope.warehouseInfo.erp_doc_type,
                    do_flag: $scope.do_flag,
                    plot_info_detail: []
                };
                if($scope.warehouseInfo.select_type == 2){
                    content.type = 2;
                //20170612 modify by Dustdusk for 新增warehouseInfo.select_type = 4 (作廢)
                } else if($scope.warehouseInfo.select_type == 4){
                    content.type = 3;
                }
                for(var index in $scope.selectedList){
                    var item = $scope.selectedList[index];
                    var plot_info_detail = {
                        plot_no: item.plot_no, 
                        lot_code: item.storage_plot,
                        op_no: item.op_no, 
                        lot_serial: item.lot_serial , 
                        plot_qty: item.qty, 
                        error_no: item.error_no
                    };

                    if($scope.warehouseInfo.select_type == 4){
                        if(item.cancel_qty == undefined || item.cancel_qty == 0){
                            msg = $filter('translate')('B0401.msg.cancel_qty_empty');
                            break;
                        } else if(item.cancel_qty == undefined || item.cancel_qty == 0){
                            msg = $filter('translate')('B0401.msg.cancel_qty_gt');
                            break;
                        }
                        plot_info_detail.cancel_qty = item.cancel_qty;
                    }
                    if($scope.type == '0'){
                        if(item.joint_trigger == undefined){
                            plot_info_detail.joint_trigger = 'N';
                        } else {
                            plot_info_detail.joint_item_no = item.joint_item_no;
                            plot_info_detail.joint_item_unit_no = item.joint_item_unit_no;
                            plot_info_detail.joint_trigger = 'Y';
                        }
                    }
                    content.plot_info_detail.push(plot_info_detail);
                    //content.op_no = item.op_no;
                }
                if(msg == ''){
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_WIP.warehouse_plot_process',
                        content: content,
                        success: function (data, response) {
                            //20180514 modify by Dustdusk for M#46940:入庫完成的訊息由後台提供 請抓 response.Message
                            var msg = $filter('translate')('B0401.msg.process_success');
                            if(response.Message != undefined && response.Message!=''){
                                msg = response.Message;
                            }
                            //20170330 modify by megabytes for 確認存取完後清空
                            $scope.warehouseInfo.plot_info_detail = [];
                            $scope.warehouseInfo.item_name = '';
                            $scope.warehouseInfo.wo_no = '';
                            $scope.warehouseInfo.plot_no = '';
                            $scope.warehouseInfo.item_no = '';
                            $scope.selectedList = [];
                            $scope.$root.showToast(msg);
                        }
                    });
                } else {
                    $scope.$root.showAlert(msg);
                }
            }

            $scope.changeSelectType = function(type){
                if($scope.warehouseInfo.select_type == 4 && type != 4){
                    $scope.selectedList.forEach(function(selectItem) {
                        selectItem.cancel_qty = undefined;
                    });
                }
                $scope.warehouseInfo.select_type = type;
            };

            $scope.input_cancel_qty = function (event, item) {
                var target = event.currentTarget;
                angular.element(target).addClass('is-focus');
                $calculater.open(function (num, dialog) {
                        angular.element(target).removeClass('is-focus');
                        if(num == 0){
                            $scope.$root.showAlert($filter('translate')('B0401.msg.cancel_qty_empty'));
                        } else if ((+num) > (+item.qty)){
                            $scope.$root.showAlert($filter('translate')('B0401.msg.cancel_qty_gt'));
                        } else {
                            item.cancel_qty = num;
                            dialog.hide();
                        }
                    },
                    function (dialog) {
                        angular.element(target).removeClass('is-focus');
                        dialog.hide();
                    },
                    {
                        defaultNum: item.cancel_qty ,
                        decimal: false
                    });
            };

            $scope.product_change = function(event, item){
                $B0223Service.init({
                    parent : 'B0401',
                    plotItem : item,
                    do_flag:$scope.do_flag,
                    close : function(newItem){
                        item.item_no = newItem.item_no;
                        item.item_name = newItem.item_name;
                        item.item_unit_no = newItem.item_unit_no;
                        item.item_ver = newItem.item_ver;
                    },
                    feedback : function(newItem){
                        item.old_item_no = item.item_no;
                        item.old_item_name = item.item_name;
                        item.old_item_unit_no = item.item_unit_no;
                        item.old_item_ver = item.item_ver;

                        item.joint_item_no = item.item_no = newItem.joint_item_no;
                        item.item_name = newItem.joint_item_name;
                        item.joint_item_unit_no = item.item_unit_no = newItem.joint_item_unit_no;
                        item.item_ver = newItem.joint_item_ver;
                        item.joint_trigger = 'Y';
                    }
                });
            };

            $scope.callB0225 = function(item){
                $B0225Service.init({
                    parent:'B0401',
                    plotItem : item,
                    callback : function(){
                        $scope.search();
                    }
                });
            };
        }
    ];
});
